<template>
	<a-form ref="formRef" :model="formData" :rules="formRules" layout="vertical" class="form-box">
		<a-row v-for="(item, index) in formOption" :key="index" :gutter="75">
			<a-col :span="8" v-for="v in item" :key="v.prop">
				<a-form-item :name="v.prop" v-if="!v.isrequire">
					<LabelDes :label="v.label" :prop="v.prop" />
					<a-input v-if="v.type === 'text'" v-model:value="formData[v.prop]" :maxlength="v.maxlength"
						:placeholder="v.placeholder" allow-clear />

					<a-select v-if="v.type === 'select'" v-model:value="formData[v.prop]" :placeholder="v.placeholder"
						:options="v.option" allow-clear />
					<a-radio-group v-if="v.type === 'radio'" v-model:value="formData[v.prop]" :options="radioOption"
						:name="v.prop" @change="radioChange" />
				</a-form-item>
				<a-form-item :name="v.prop" v-if="v.isrequire">
					<LabelDes :label="v.label" :prop="v.prop" />
					<a-input v-if="v.type === 'text'" v-model:value="formData[v.prop]" :maxlength="v.maxlength"
						:placeholder="v.placeholder" :disabled="v.prop === 'singlepointUrl'" allow-clear />
					<a-input v-if="v.type === 'appUrl'" :maxlength="v.maxlength" v-model:value="formData[v.prop]"
						:placeholder="v.placeholder" @change="appUrlChange" allow-clear />
					<!-- <a-date-picker ref="picks" v-if="v.type === 'date'" style="width: 100%" valueFormat="YYYY-MM-DD"
						:showToday="false" v-model:value="formData[v.prop]">
					</a-date-picker> -->
				</a-form-item>
			</a-col>
		</a-row>
		<div>
			<a-row v-for="(item, index) in formOptionDb" :key="index" :gutter="75">
				<a-col :span="8" v-for="v in item" :key="v.prop">
					<a-form-item :name="v.prop">
						<LabelDes :label="v.label" :prop="v.prop" :isRequ="isPcTodo === '1'" />
						<a-input v-if="v.type === 'text'" v-model:value="formData[v.prop]" :maxlength="v.maxlength"
							:placeholder="v.placeholder" :disabled="isPcTodo == '0'" allow-clear />
						<a-input-password v-if="v.type === 'password'" v-model:value="formData[v.prop]"
							:maxlength="v.maxlength" :placeholder="v.placeholder" :disabled="isPcTodo == '0'" />
						<a-select v-if="v.type === 'select'" v-model:value="formData[v.prop]"
							:placeholder="v.placeholder" :options="v.option" :disabled="isPcTodo == '0'" allow-clear />
					</a-form-item>
				</a-col>
			</a-row>
		</div>
		<div>
			<a-row v-for="(item, index) in formOptionDy" :key="index" :gutter="75">
				<a-col :span="8" v-for="v in item" :key="v.prop">
					<a-form-item :name="v.prop">
						<LabelDes :label="v.label" :prop="v.prop" :isRequ="isPcTodo === '1' && isPcReadtodo === '1'" />
						<a-input v-if="v.type === 'text'" v-model:value="formData[v.prop]"
							:disabled="isPcReadtodo == '0'" :placeholder="v.placeholder" allow-clear />
						<a-input-password v-if="v.type === 'password'" v-model:value="formData[v.prop]"
							:disabled="isPcReadtodo == '0'" :placeholder="v.placeholder" />
						<a-select v-if="v.type === 'select'" v-model:value="formData[v.prop]"
							:placeholder="v.placeholder" :disabled="isPcReadtodo == '0'" :options="v.option" />
					</a-form-item>
				</a-col>
			</a-row>
		</div>

		<a-row :gutter="75">
			<a-col :span="8">
				<a-form-item name="compatibility">
					<LabelDes label="兼容性" prop="compatibility" />
					<a-checkbox-group v-model:value="formData.compatibility" :options="compatibleOptions" />
				</a-form-item>
			</a-col>
			<a-col :span="8">
				<a-form-item name="authType">
					<LabelDes label="认证状态" prop="authType" />
					<a-select v-model:value="formData.authType" placeholder="基本认证" :options="tool.dictList('CERTIFIED')"
						allow-clear />
				</a-form-item>
			</a-col>
			<a-col :span="8">
				<a-form-item name="pcLogo">
					<LabelDes label="门户端应用logo" prop="pcLogo" />
					<div class="upload-box">
						<a-upload v-model:file-list="fileList" name="avatar" list-type="picture-card"
							class="avatar-uploader" :customRequest="customRequest" :accept="fileImgType"
							:before-upload="beforeUpload" @change="handleChange" @preview="handlePreview">
							<div v-if="fileList?.length == 0">
								<plus-outlined></plus-outlined>
								<div class="ant-upload-text">上传图片</div>
							</div>
						</a-upload>
						<div class="annotation">
							<div class="tit1">*注</div>
							<div>1.应用logo需要满足UI/UE规范;</div>
							<div>2.需要上传.png/.jpg/.jpeg格式文件;</div>
							<div>3.文件大小为不超过200K;</div>
						</div>
					</div>
				</a-form-item>
			</a-col>
		</a-row>
		<a-modal :visible="previewVisible" :footer="null" @cancel="handleCancel">
			<img alt="example" style="width: 100%" :src="imageUrl" />
		</a-modal>
	</a-form>
</template>

<script setup name="PortalForm">
import LabelDes from '../../LabelDes.vue'
import fileApi from '@/api/dev/fileApi'
import tool from '@/utils/tool'
import { message } from 'ant-design-vue'
import { cloneDeep } from 'lodash-es'
import sysConfig from '@/config/index'
import store from '@/store'
import { useRoute } from 'vue-router'
const route = useRoute()
const { isImport } = route.query
const fileUrl = import.meta.env.VITE_FILE_URL
const fileImgType = '.jpg,.png,.jpeg,'
const formRef = ref()
// const picks = ref()
// 表单数据
const formData = ref({
	isAuth: '1',
	isSinglepoint: '1',
	isHideLogo: '1',
	pcLogo: '',
	pcVersion: '1.0',
	pendingDatasourcePassword: '135790',
	readingDatasourcePassword: '135790'
})
// 单选option
const radioOption = [
	{ label: '是', value: '1' },
	{ label: '否', value: '0' }
]
const valiUrl = async (_, value) => {
	if (!value) {
		return Promise.reject('请输入')
	}
	if (/[\u4E00-\u9FA5]/g.test(value)) {
		return Promise.reject('不能输入汉字!')
	}
	return Promise.resolve()
}
const valiFont = async (_, value) => {
	if (!value) {
		return Promise.reject('请输入版本说明')
	}
	if (value.length < 5) {
		return Promise.reject('不能少于5个字!')
	}
	return Promise.resolve()
}
const valiFontFive = async (rule, value) => {
	if (rule.required && !value) {
		return Promise.reject('请输入地址')
	}
	if (rule.required && value.length > 50) {
		return Promise.reject('不能大于50个字!')
	}
	return Promise.resolve()
}
const valiMail = async (rule, value) => {
	const reg = /^[a-zA-Z0-9][\w\.-]*@[a-zA-Z0-9-]+\.[a-zA-Z]{2,}(\.[a-zA-Z]{2,})?$/;
	if (rule.required && !value) {
		return Promise.reject('请输入对端系统管理人邮箱')
	}
	if (rule.required && !reg.test(value)) {
		return Promise.reject('请输入正确的邮箱!')
	}
	return Promise.resolve()
}
// 兼容option
const compatibleOptions = ['IE8', 'IE9', 'IE10', 'IE11', 'chrome', 'firefox', '其他']
const changeRulesDB = reactive({
	pendingCategory: [{ required: true, message: '请输入待办所属分类', trigger: 'blur' }],
	pendingDatasourceUrl: [{ required: true, message: '请输入待办稽核地址', trigger: 'blur' }],
	pendingDatasourceType: [{ required: true, message: '请输入数据库类型', trigger: 'blur' }],
	pendingDatasourceUsername: [{ required: true, message: '请输入数据库账号', trigger: 'blur' }],
	// pendingDatasourcePassword: [{ required: true, message: '请输入数据库密码', trigger: 'blur' }],
	pendingTablename: [{ required: true, validator: valiFontFive, trigger: 'blur' }],
	pendingUserMail: [{ required: true, validator: valiMail, trigger: 'blur' }]
})
const changeRulesDY = reactive({
	readingCategory: [{ required: true, message: '请输入待办所属分类', trigger: 'blur' }],
	readingDatasourceUrl: [{ required: true, message: '请输入待阅稽核地址', trigger: 'blur' }],
	readingDatasourceType: [{ required: true, message: '请输入数据库类型', trigger: 'blur' }],
	readingDatasourceUsername: [{ required: true, message: '请输入数据库账号', trigger: 'blur' }],
	// readingDatasourcePassword: [{ required: true, message: '请输入数据库密码', trigger: 'blur' }],
	readingTablename: [{ required: true, message: '请输入待阅核视图地址', trigger: 'blur' }],
	readingUserMail: [{ required: true, validator: valiMail, trigger: 'blur' }]
})
const rules = [{ required: true, validator: valiUrl, tirgger: 'blur' }]
// 默认要校验的
const formRules = reactive({

	appInfoKeywords: [{ required: true, message: '请输入应用关键字', tirgger: 'blur' }],
	// pcOnlineTime: [{ required: true, message: '请选择时间', tirgger: 'blur' }],
	pcVersionNote: [{ required: true, validator: valiFont, trigger: 'blur' }],
	isAuth: [{ required: true, message: '', trigger: 'blur' }],
	isSinglepoint: [{ required: true, message: '', trigger: 'blur' }],
	singlepointUrl: [{ required: true, message: '单点地址', tirgger: 'blur' }],
	compatibility: [{ required: true, message: '请选择兼容性', trigger: 'blur' }],
	authType: [{ required: true, message: '请选择认证状态', trigger: 'blur' }],
	pcLogo: [{ required: true, message: '请选择logo', trigger: 'blur' }],
	appShortName: [{ required: true, message: '请输入应用简称', trigger: 'blur' }],
	appTutorials: [{ required: true, message: '请输入应用教程', trigger: 'blur' }],
	appUrl: [{ required: true, validator: valiUrl, trigger: 'blur' }],
	batchReadUrl: [{ required: true, message: '请输入批量已阅地址', trigger: 'blur' }],
	...changeRulesDY,
	...changeRulesDB
})
const formOption = [
	[
		// { label: '版本号', type: 'text', prop: 'pcVersion', placeholder: '请输入版本号'},
		{
			label: '应用关键字',
			type: 'text',
			prop: 'appInfoKeywords',
			placeholder: '请输入应用关键字'
		},
		{
			label: '版本说明',
			type: 'text',
			prop: 'pcVersionNote',
			placeholder: '请输入版本说明不超过30字',
			maxlength: 30,
		},
		{
			label: '是否鉴权',
			type: 'radio',
			prop: 'isAuth',
			placeholder: '',
			option: radioOption,
		},
		{
			label: '是否单点',
			type: 'radio',
			prop: 'isSinglepoint',
			placeholder: '',
			option: radioOption,
		},
		{
			label: '是否展示图标',
			type: 'radio',
			prop: 'isHideLogo',
			placeholder: '',
			option: radioOption,
		},
		// {
		// 	label: '门户端应用上线时间',
		// 	type: 'date',
		// 	prop: 'pcOnlineTime',
		// 	isrequire: true,
		// 	placeholder: '',
		// },
	],
	[
		// { label: '是否显示', type: 'radio', prop: 'is_show', placeholder: '', option: radioOption },
		{
			label: '应用地址',
			isrequire: true,
			type: 'appUrl',
			prop: 'appUrl',
			placeholder: '请输入应用地址不能超过200字',
			maxlength: 200,
		},

		{
			label: '单点地址',
			isrequire: true,
			type: 'text',
			prop: 'singlepointUrl',
			placeholder: '单点地址不能超过200字',
			maxlength: 200
		},

		{
			label: '应用简称',
			type: 'text',
			prop: 'appShortName',
			placeholder: '请输入应用简称',
			maxlength: 6,
		},
		{
			label: '应用教程',
			type: 'text',
			prop: 'appTutorials',
			placeholder: '请输入应用教程不超过200字',
			maxlength: 200
		}
	],
	[
		{
			label: '批量已阅地址',
			isrequire: true,
			type: 'text',
			prop: 'batchReadUrl',
			placeholder: '请输入单点地址不超过80字',
			maxlength: 80
		}
	]
]
const formOptionDb = [
	[
		{
			label: '待办所属分类',
			type: 'select',
			prop: 'pendingCategory',
			placeholder: '请输入待办所属分类',
			option: tool.dictList('TODO_TYPE'),
		},
		{
			label: '待办稽核地址',
			type: 'text',
			prop: 'pendingDatasourceUrl',
			placeholder: '请输入待办稽核地址',
			maxlength: 500
		},
		{
			label: '数据库类型',
			type: 'text',
			prop: 'pendingDatasourceType',
			placeholder: '请输入数据库类型不超过30字',
			maxlength: 30
		}
	],
	[
		{
			label: '数据库账号',
			type: 'text',
			prop: 'pendingDatasourceUsername',
			placeholder: '请输入数据库账号',
			maxlength: 50
		},
		// {
		// 	label: '数据库密码',
		// 	type: 'password',
		// 	prop: 'pendingDatasourcePassword',
		// 	placeholder: '请输入数据库密码',
		// 	maxlength: 50
		// },
		{
			label: '待办核视图地址',
			type: 'text',
			prop: 'pendingTablename',
			placeholder: '请输入待办核视图地址',
		}
	],
	[
		{
			label: '对端系统管理人邮箱',
			type: 'text',
			prop: 'pendingUserMail',
			placeholder: '请输入对端系统管理人邮箱',
		}
	]
]
const formOptionDy = [
	[
		{
			label: '待阅所属分类',
			type: 'select',
			prop: 'readingCategory',
			placeholder: '请输入待阅所属分类',
			option: tool.dictList('TODO_TYPE'),
		},
		{
			label: '待阅稽核地址',
			type: 'text',
			prop: 'readingDatasourceUrl',
			placeholder: '请输入待阅稽核地址',
		},
		{
			label: '数据库类型',
			type: 'text',
			prop: 'readingDatasourceType',
			placeholder: '请输入数据库类型',
		}
	],
	[
		{
			label: '数据库账号',
			type: 'text',
			prop: 'readingDatasourceUsername',
			placeholder: '请输入数据库账号',
		},
		// {
		// 	label: '数据库密码',
		// 	type: 'password',
		// 	prop: 'readingDatasourcePassword',
		// 	placeholder: '请输入数据库密码',
		// },
		{
			label: '待阅核视图地址',
			type: 'text',
			prop: 'readingTablename',
			placeholder: '请输入待阅核视图地址',
		}
	],
	[
		{
			label: '对端系统管理人邮箱',
			type: 'text',
			prop: 'readingUserMail',
			placeholder: '请输入对端系统管理人邮箱',
		}
	]
]

const fileList = ref([])
const loading = ref(false)
const imageUrl = ref('')
let previewVisible = ref(false)
/*变更编辑  开始*/
const editDate = inject('editDate')
const forData = () => {
	if (formData.value.pcLogo) {
		if (formData.value.pcLogo.includes('group')) {
			fileList.value = [{ url: `${sysConfig.FULL_URL}${formData.value.pcLogo}` }]
			imageUrl.value = `${sysConfig.FULL_URL}${formData.value.pcLogo}`
		} else {
			fileList.value = formData.value.pcLogo ? JSON.parse(formData.value.pcLogo) : []
			fileList.value.forEach((item) => {
				item.url = `${fileUrl}/${item.url}`
			})
		}
	}
	if (!Array.isArray(formData.value.compatibility)) {
		formData.value.compatibility = formData.value.compatibility ? formData.value.compatibility.split(',') : []
	}
	formRules.singlepointUrl[0].required = formData.value.isSinglepoint == 1 ? true : false
}
const isEdit = computed(() => {
	let bool = false
	bool = editDate.value
	return bool
})
onMounted(() => {
	if (isEdit.value) {
		formData.value = cloneDeep(editDate.value?.appInfoPcPropertiesAddParam || editDate.value?.pcPropertiesList[0])
		forData()
	}
})

/*变更编辑  结束*/
// 导入成功
const importOk = inject('importOk')
if (importOk?.value) {
	let datas = store.state.appinfo.importData
	if (datas?.appInfoPcPropertiesAddParam) {
		formData.value = cloneDeep(datas?.appInfoPcPropertiesAddParam)
		forData()
	}
}

// 是否单点变化事件
const radioChange = (e) => {
	const { name, value } = e.target
	if (name === 'isSinglepoint') {
		if (value === '1') {
			// 单点地址必填
			formRules.singlepointUrl[0].required = true
			formData.value.singlepointUrl = formData.value.appUrl
		} else {
			formRules.singlepointUrl[0].required = false
			formData.value.singlepointUrl = null
		}
	}
}
const appUrlChange = (e) => {
	const { value } = e.target
	if (value) {
		if (formData.value.isSinglepoint == '1') {
			formData.value.singlepointUrl = value
		}
	}
}

// 自定义上传
const customRequest = (file) => {
	// 后端需要接受的参数是 formData数据，
	const form = new FormData()
	form.append('file', file.file)
	fileApi
		.uploadCosReturnUrlPub(form)
		.then((res) => {
			let arr = [{ name: file.file.name, url: res }]
			formData.value.pcLogo = JSON.stringify(arr)
			file.onSuccess(res, file.file)
			file.status = 'done'
		})
		.catch((err) => {
			setTimeout(() => {
				file.onError()
			}, 1000)
		})
}
const getBase64 = (img, callback) => {
	const reader = new FileReader()
	reader.addEventListener('load', () => callback(reader.result))
	reader.readAsDataURL(img)
}
const handleChange = (info) => {
	const { type, size } = info.file
	const isJpgOrPng = type === 'image/jpeg' || type === 'image/png' || type === 'image/jpg'
	const isLt2K = size / 1024 < 200
	if (!isJpgOrPng && info.file.status !== 'removed') {
		message.warning('图片类型不对')
		fileList.value = []
		return false
	}
	if (!isLt2K && info.file.status !== 'removed') {
		message.warning('图片大小不超过200K')
		fileList.value = []
		return false
	}
	if (info.file.status === 'uploading') {
		loading.value = true
		return
	}


	if (info.file.status === 'uploading') {
		loading.value = true
		return
	}
	if (info.file.status === 'done') {
		// Get this url from response in real world.
		getBase64(info.file.originFileObj, (base64Url) => {
			imageUrl.value = base64Url
			loading.value = false
		})
	}
	if (info.file.status === 'error') {
		loading.value = false
		fileList.value = []
		// message.error('上传失败')
	}
	if (info.file.status === 'removed') {
		formData.value.pcLogo = ''
	}
}
const beforeUpload = (file) => {
	const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png' || file.type === 'image/jpg'
	const isLt2K = file.size / 1024 < 200
	return isJpgOrPng && isLt2K
}
const handlePreview = () => {
	previewVisible.value = true
}
const handleCancel = () => {
	previewVisible.value = false
}

// 监听是否接入待办修改待办相关必填非必填
// pc待办选择是 待阅可以选择是否
const isPcTodo = inject('isPcTodo')
watch(
	isPcTodo,
	(newData) => {
		// Object.keys(formRules).forEach((v) => {
		// 	if (v.includes('pending') || v.includes('reading')) {
		// 		formRules[v][0].required = newData == '1' ? true : false
		// 	}
		// })
		// console.log(formRules)
		// 根据待办选择是否切换待办待阅数据
		if (newData == '1') {
			// 待办选择是
			if (isEdit.value) {
				let obj = editDate.value?.appInfoPcPropertiesAddParam || editDate.value?.pcPropertiesList[0]
				// 如果是修改,赋值
				Object.keys(changeRulesDB).forEach((v) => {
					formData.value[v] = obj[v]
				})
				Object.keys(changeRulesDY).forEach((v) => {
					formData.value[v] = obj[v]
				})
				Object.keys(formRules).forEach((v) => {
					if (v.includes('pending')) {
						formRules[v][0].required = newData == '1' ? true : false
					}
				})
			}
		} else {
			// 待办选择否-清空
			Object.keys(changeRulesDB).forEach((v) => {
				formData.value[v] = ''
			})
			Object.keys(changeRulesDY).forEach((v) => {
				formData.value[v] = ''
			})
			Object.keys(formRules).forEach((v) => {
				if (v.includes('pending')) {
					formRules[v][0].required = newData == '1' ? true : false
				}
			})
		}
	},
	{ deep: true, immediate: true }
)
// 监听是否接入待阅修改待阅相关必填非必填
const isPcReadtodo = inject('isPcReadtodo')
watch(
	isPcReadtodo,
	(newData) => {
		Object.keys(formRules).forEach((v) => {
			if (v.includes('reading')) {
				formRules[v][0].required = newData == '1' ? true : false
			}
		})
		formRules.batchReadUrl[0].required = newData == '1' ? true : false
	},
	{ deep: true, immediate: true }
)

// input内容发生变化 给待阅赋值
const handleChangeInput = (e) => {
	const { value, id } = e.target
	const key = id.split('_').pop().replace('pen', 'rea')
	formData.value[key] = value
}
const handleChangeSelect = (value) => {
	formData.value['readingCategory'] = value
}
const filt = () => {
	let obj = cloneDeep(formData.value);
	let arrFlat = []
	if (isPcTodo.value == '0') {
		arrFlat = formOptionDb.flat();
		arrFlat.forEach(v => {
			obj[v.prop] = null
		})
	}
	if (isPcReadtodo.value == '0') {
		arrFlat = formOptionDy.flat();
		arrFlat.forEach(v => {
			obj[v.prop] = null
		})
	}
	return obj
}
// 表单验证
const handleValidate = () => {
	return new Promise((resolve, reject) => {
		formRef.value
			.validate()
			.then(() => {
				console.log('成功')
				resolve(filt())
			})
			.catch(() => {
				console.log('失败')
				resolve(false)
			})
	})
}
defineExpose({ handleValidate })
</script>

<style lang="less" scoped>
.form-box {
	margin-top: 14px;

	.upload-box {
		display: flex;

		.annotation {
			font-size: 12px;
			color: rgb(150, 150, 150);
			line-height: 22px;
			margin-left: 10px;

			.tit1 {
				color: rgb(194, 0, 0);
			}
		}
	}

	.labelCla {
		padding: 0 0 8px;

		.label-fon {
			margin-right: 10px;
		}
	}

	&-inp {
		border-radius: 4px;
		border: 1px solid rgb(206, 206, 206);
	}
}

// .labelCla::before {
//     display: inline-block;
//     margin-right: 4px;
//     color: var(--highlight-color);
//     font-size: 14px;
//     font-family: SimSun, sans-serif;
//     line-height: 1;
//     content: '*';
// }

.brfr::before {
	display: inline-block;
	margin-right: 4px;
	color: var(--highlight-color);
	font-size: 14px;
	font-family: SimSun, sans-serif;
	line-height: 1;
	content: '*';
}
</style>
<style>
.avatar-uploader>.ant-upload {
	width: 104px;
	height: 104px;
}

.ant-upload-select-picture-card i {
	font-size: 32px;
	color: #999;
}

.ant-upload-select-picture-card .ant-upload-text {
	margin-top: 8px;
	color: #666;
}
</style>
